import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import '../models/expense_model.dart';
import '../providers/expense_providers.dart';
import '../themes/expense_theme.dart';
import 'enhanced_date_picker.dart';

/// 记账搜索和过滤组件
class ExpenseSearchFilter extends ConsumerStatefulWidget {
  const ExpenseSearchFilter({super.key});

  @override
  ConsumerState<ExpenseSearchFilter> createState() => _ExpenseSearchFilterState();
}

class _ExpenseSearchFilterState extends ConsumerState<ExpenseSearchFilter>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final _searchController = TextEditingController();
  ExpenseType? _selectedType;
  ExpenseCategory? _selectedCategory;
  DateTimeRange? _selectedDateRange;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    _searchController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: ExpenseTheme.cardBackground,
        borderRadius: BorderRadius.circular(20.r),
        boxShadow: ExpenseTheme.cardShadow,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          _buildHeader(),
          _buildTabBar(),
          _buildTabContent(),
        ],
      ),
    );
  }

  /// 构建头部
  Widget _buildHeader() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            ExpenseTheme.primaryBlue.withValues(alpha: 0.1),
            ExpenseTheme.lightBlue.withValues(alpha: 0.05),
          ],
        ),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.r),
          topRight: Radius.circular(20.r),
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.search,
            color: ExpenseTheme.primaryBlue,
            size: 24.sp,
          ),
          SizedBox(width: 12.w),
          Text(
            '搜索与筛选',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
              color: ExpenseTheme.textPrimary,
            ),
          ),
          const Spacer(),
          IconButton(
            onPressed: _clearAllFilters,
            icon: Icon(
              Icons.clear_all,
              color: ExpenseTheme.textSecondary,
              size: 20.sp,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建标签栏
  Widget _buildTabBar() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      decoration: BoxDecoration(
        color: ExpenseTheme.softBlue,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: TabBar(
        controller: _tabController,
        indicator: BoxDecoration(
          color: ExpenseTheme.primaryBlue,
          borderRadius: BorderRadius.circular(12.r),
        ),
        labelColor: Colors.white,
        unselectedLabelColor: ExpenseTheme.textSecondary,
        labelStyle: TextStyle(
          fontSize: 14.sp,
          fontWeight: FontWeight.w600,
        ),
        tabs: const [
          Tab(text: '搜索'),
          Tab(text: '筛选'),
        ],
      ),
    );
  }

  /// 构建标签内容
  Widget _buildTabContent() {
    return Container(
      height: 300.h,
      padding: EdgeInsets.all(16.w),
      child: TabBarView(
        controller: _tabController,
        children: [
          _buildSearchTab(),
          _buildFilterTab(),
        ],
      ),
    );
  }

  /// 构建搜索标签页
  Widget _buildSearchTab() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '关键词搜索',
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.w600,
            color: ExpenseTheme.textPrimary,
          ),
        ),
        SizedBox(height: 12.h),
        TextField(
          controller: _searchController,
          decoration: InputDecoration(
            hintText: '搜索备注或分类名称',
            prefixIcon: Icon(
              Icons.search,
              color: ExpenseTheme.primaryBlue,
            ),
            suffixIcon: _searchController.text.isNotEmpty
                ? IconButton(
                    onPressed: () {
                      _searchController.clear();
                      _updateSearch();
                    },
                    icon: Icon(
                      Icons.clear,
                      color: ExpenseTheme.textSecondary,
                    ),
                  )
                : null,
            filled: true,
            fillColor: ExpenseTheme.softBlue,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12.r),
              borderSide: BorderSide.none,
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12.r),
              borderSide: BorderSide(color: ExpenseTheme.lightBlue),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12.r),
              borderSide: BorderSide(color: ExpenseTheme.primaryBlue, width: 2),
            ),
          ),
          onChanged: (_) => _updateSearch(),
        ),
        SizedBox(height: 16.h),
        Text(
          '搜索结果',
          style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.w500,
            color: ExpenseTheme.textSecondary,
          ),
        ),
        SizedBox(height: 8.h),
        Expanded(
          child: _buildSearchResults(),
        ),
      ],
    );
  }

  /// 构建筛选标签页
  Widget _buildFilterTab() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 类型筛选
        _buildFilterSection(
          '记账类型',
          Icons.category,
          _buildTypeFilter(),
        ),
        SizedBox(height: 16.h),
        
        // 日期范围筛选
        _buildFilterSection(
          '日期范围',
          Icons.date_range,
          _buildDateRangeFilter(),
        ),
        SizedBox(height: 16.h),
        
        // 分类筛选
        _buildFilterSection(
          '分类筛选',
          Icons.label,
          _buildCategoryFilter(),
        ),
      ],
    );
  }

  /// 构建筛选区块
  Widget _buildFilterSection(String title, IconData icon, Widget content) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Icon(icon, color: ExpenseTheme.primaryBlue, size: 16.sp),
            SizedBox(width: 8.w),
            Text(
              title,
              style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w600,
                color: ExpenseTheme.textPrimary,
              ),
            ),
          ],
        ),
        SizedBox(height: 8.h),
        content,
      ],
    );
  }

  /// 构建类型筛选
  Widget _buildTypeFilter() {
    return Row(
      children: [
        Expanded(
          child: _buildFilterChip(
            '收入',
            _selectedType == ExpenseType.income,
            () => _updateTypeFilter(ExpenseType.income),
            ExpenseTheme.incomeGreen,
          ),
        ),
        SizedBox(width: 8.w),
        Expanded(
          child: _buildFilterChip(
            '支出',
            _selectedType == ExpenseType.expense,
            () => _updateTypeFilter(ExpenseType.expense),
            ExpenseTheme.expenseRed,
          ),
        ),
      ],
    );
  }

  /// 构建日期范围筛选
  Widget _buildDateRangeFilter() {
    return InkWell(
      onTap: _selectDateRange,
      borderRadius: BorderRadius.circular(8.r),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
        decoration: BoxDecoration(
          color: ExpenseTheme.softBlue,
          borderRadius: BorderRadius.circular(8.r),
          border: Border.all(color: ExpenseTheme.lightBlue),
        ),
        child: Row(
          children: [
            Icon(
              Icons.calendar_today,
              color: ExpenseTheme.primaryBlue,
              size: 16.sp,
            ),
            SizedBox(width: 8.w),
            Text(
              _selectedDateRange != null
                  ? '${DateFormat('MM/dd').format(_selectedDateRange!.start)} - ${DateFormat('MM/dd').format(_selectedDateRange!.end)}'
                  : '选择日期范围',
              style: TextStyle(
                fontSize: 12.sp,
                color: _selectedDateRange != null
                    ? ExpenseTheme.textPrimary
                    : ExpenseTheme.textSecondary,
              ),
            ),
            const Spacer(),
            if (_selectedDateRange != null)
              GestureDetector(
                onTap: () {
                  setState(() {
                    _selectedDateRange = null;
                  });
                  _updateFilters();
                },
                child: Icon(
                  Icons.clear,
                  color: ExpenseTheme.textSecondary,
                  size: 16.sp,
                ),
              ),
          ],
        ),
      ),
    );
  }

  /// 构建分类筛选
  Widget _buildCategoryFilter() {
    final categories = _selectedType == ExpenseType.income
        ? ExpenseCategoryExtension.incomeCategories
        : _selectedType == ExpenseType.expense
            ? ExpenseCategoryExtension.expenseCategories
            : [...ExpenseCategoryExtension.incomeCategories, ...ExpenseCategoryExtension.expenseCategories];

    return Wrap(
      spacing: 8.w,
      runSpacing: 8.h,
      children: categories.take(6).map((category) {
        final isSelected = _selectedCategory == category;
        return _buildFilterChip(
          category.displayName,
          isSelected,
          () => _updateCategoryFilter(category),
          ExpenseTheme.primaryBlue,
        );
      }).toList(),
    );
  }

  /// 构建筛选芯片
  Widget _buildFilterChip(
    String label,
    bool isSelected,
    VoidCallback onTap,
    Color color,
  ) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(16.r),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
        decoration: BoxDecoration(
          color: isSelected ? color.withValues(alpha: 0.1) : ExpenseTheme.softBlue,
          borderRadius: BorderRadius.circular(16.r),
          border: Border.all(
            color: isSelected ? color : ExpenseTheme.lightBlue,
            width: isSelected ? 2 : 1,
          ),
        ),
        child: Text(
          label,
          style: TextStyle(
            fontSize: 12.sp,
            fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
            color: isSelected ? color : ExpenseTheme.textSecondary,
          ),
        ),
      ),
    );
  }

  /// 构建搜索结果
  Widget _buildSearchResults() {
    final searchedExpenses = ref.watch(searchedExpensesProvider);
    
    if (searchedExpenses.isEmpty) {
      return Center(
        child: Text(
          '暂无搜索结果',
          style: TextStyle(
            fontSize: 14.sp,
            color: ExpenseTheme.textSecondary,
          ),
        ),
      );
    }

    return ListView.builder(
      itemCount: searchedExpenses.length,
      itemBuilder: (context, index) {
        final expense = searchedExpenses[index];
        return ListTile(
          leading: Text(expense.category.icon, style: TextStyle(fontSize: 20.sp)),
          title: Text(expense.category.displayName),
          subtitle: Text(expense.description),
          trailing: Text(
            '¥${expense.amount.toStringAsFixed(2)}',
            style: TextStyle(
              color: expense.type == ExpenseType.income
                  ? ExpenseTheme.incomeGreen
                  : ExpenseTheme.expenseRed,
              fontWeight: FontWeight.w600,
            ),
          ),
        );
      },
    );
  }

  /// 更新搜索
  void _updateSearch() {
    ref.read(searchKeywordProvider.notifier).state = _searchController.text;
  }

  /// 更新类型筛选
  void _updateTypeFilter(ExpenseType type) {
    setState(() {
      _selectedType = _selectedType == type ? null : type;
      _selectedCategory = null; // 重置分类选择
    });
    _updateFilters();
  }

  /// 更新分类筛选
  void _updateCategoryFilter(ExpenseCategory category) {
    setState(() {
      _selectedCategory = _selectedCategory == category ? null : category;
    });
    _updateFilters();
  }

  /// 选择日期范围
  Future<void> _selectDateRange() async {
    final dateRange = await showDateRangePicker(
      context: context,
      firstDate: DateTime(2020),
      lastDate: DateTime.now(),
      initialDateRange: _selectedDateRange,
    );

    if (dateRange != null) {
      setState(() {
        _selectedDateRange = dateRange;
      });
      _updateFilters();
    }
  }

  /// 更新筛选
  void _updateFilters() {
    ref.read(selectedDateRangeProvider.notifier).state = _selectedDateRange;
    // 这里可以添加更多筛选逻辑
  }

  /// 清除所有筛选
  void _clearAllFilters() {
    setState(() {
      _searchController.clear();
      _selectedType = null;
      _selectedCategory = null;
      _selectedDateRange = null;
    });
    ref.read(searchKeywordProvider.notifier).state = '';
    ref.read(selectedDateRangeProvider.notifier).state = null;
  }
}
